package com.metro.generator.gen.util;

import com.metro.generator.gen.beans.constant.GenConstant;
import com.metro.generator.gen.GeneratorProperties;
import com.metro.generator.gen.beans.vo.GenTable;
import com.metro.generator.gen.beans.vo.GenTableColumn;
import com.metro.utils.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Iterator;
import java.util.List;
import java.util.Properties;


/**
 * 生成器帮助类
 * Created by xk on 2018/1/19 0019.
 */
public class GenUtil {
    private static Logger log = LoggerFactory.getLogger(GenUtil.class);
    /**
     * 根据数据库表的基本信息初始化默认参数
     * @param genTable
     */
    public static void initTableAndColumn(GenTable genTable) {
        initTable(genTable);
        initColumn(genTable);
    }

    private static void initColumn(GenTable genTable) {
        List<GenTableColumn> columns = genTable.getColumns();
        Iterator<GenTableColumn> tableColumnIterator = columns.iterator();
        GenTableColumn entity = null;
        while(tableColumnIterator.hasNext()){
            entity = tableColumnIterator.next();

            if(isBaseColumn(entity)){
                tableColumnIterator.remove();
                continue;
            }

            entity.setIsInsert(true);
            entity.setIsRequire(true);
            entity.setIsInfo(true);
            entity.setIsList(true);
            entity.setIsQuery(false);
            entity.setJavaField(StringUtil.toCamelCase(entity.getColumnName()));

            String columnType = entity.getColumnType();
            entity.setJdbcType(getJdbcType(columnType));
            entity.setFormType(getFormType(columnType));
            // 设置java类型
            if (StringUtils.startsWithIgnoreCase(columnType, "VARCHAR")
                    || StringUtils.startsWithIgnoreCase(columnType, "NARCHAR")){
                entity.setJavaType("String");
            }else if(StringUtils.startsWithIgnoreCase(columnType, "CHAR")){
                String length = StringUtils.substringBetween(columnType, "(", ")");
                if(Integer.valueOf(length).equals(1)){
                    entity.setJavaType("Boolean");
                }else{
                    entity.setJavaType("String");
                }
            }
            else if (StringUtils.startsWithIgnoreCase(columnType, "DATETIME")
                    || StringUtils.startsWithIgnoreCase(columnType, "DATE")
                    || StringUtils.startsWithIgnoreCase(columnType, "TIMESTAMP")){
                entity.setJavaType("Date");
            }else if (StringUtils.startsWithIgnoreCase(columnType, "BIGINT")) {
                entity.setJavaType("Long");
            }else if (StringUtils.startsWithIgnoreCase(columnType, "INT")){
                entity.setJavaType("Integer");
            }else if(StringUtils.startsWithIgnoreCase(columnType, "NUMBER")){
                // 如果是浮点型
                String[] ss = StringUtils.split(StringUtils.substringBetween(columnType, "(", ")"), ",");
                if (ss != null && ss.length == 2 && Integer.parseInt(ss[1])>0){
                    entity.setJavaType("Double");
                } else if (ss != null && ss.length == 1 && Integer.parseInt(ss[0])<=10){
                    //如果是整形
                    entity.setJavaType("Integer");
                } else{
                    // 长整形
                    entity.setJavaType("Long");
                }
            }else{
                log.info("字段={},类型={}，未匹配到java类型", entity.getColumnName(), columnType);
                entity.setJavaType("String");
            }
        }
    }

    /**
     * 判断字段是否是基础字段
     * @param entity
     * @return
     */
    private static boolean isBaseColumn(GenTableColumn entity) {
        Properties props = GeneratorProperties.loadGeneratorProperties();
        String baseColumn = GenConstant.getBaseColumns(props);
        if(StringUtil.isNotEmpty(baseColumn)){
            String[] columns = baseColumn.split(",");
            for(String column : columns){
                if(entity.getColumnName().equalsIgnoreCase(column)){
                    return true;
                }
            }
        }
        return false;
    }

    private static String getFormType(String javaType) {
        if(javaType.equals("Date")){
            return "date";
        }else{
            return "text";
        }
    }

    private static String getJdbcType(String columnType) {
        String str = columnType;
        if(str.indexOf("(") > 0){
            str = str.substring(0, str.indexOf("("));
        }
        return str.toUpperCase();
    }

    private static void initTable(GenTable genTable){
        String tableName = genTable.getTableName();
        genTable.setClassName(StringUtil.toCapitalizeCamelCase(tableName));
        genTable.setFunctionName(genTable.getFunctionRemark());
        genTable.setPermissionCode(tableName.toUpperCase());
        genTable.setColumnNum(2);
        genTable.setIsConfig(false);
        String pkg = null;
        if(tableName.indexOf(StringUtil.SEPARATOR) > 0){
            pkg = tableName.substring(0, tableName.indexOf(StringUtil.SEPARATOR)).toLowerCase();
        }
        genTable.setModulePackage(pkg);
        genTable.setUrlPre(StringUtil.toCamelCase(tableName));

    }
}
